<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId">
        <el-form-item label="登录账号" prop="username">
          <el-input placeholder="请输入登录账号" v-model="searchParams.username" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="nickname">
          <el-input placeholder="请输入用户名称" v-model="searchParams.nickname" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input placeholder="请输入手机号" v-model="searchParams.mobile" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="注册时间" prop="createdTime">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            range-separator="至"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <!-- 数据表格 :data="tableList" -->
      <el-table
        v-loading="loading"
        v-adaptive
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="用户名"
          prop="username"
          width="120px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="头像" prop="avatar" width="80px" align="center">
          <template #default="scope">
            <div class="flex justify-center">
              <el-image
                class="rounded-full w-36px h-36px"
                :preview-teleported="true"
                :preview-src-list="[scope.row.avatar]"
                :src="
                  scope.row.avatar != null && scope.row.avatar !== ''
                    ? scope.row.avatar
                    : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                "
              >
                <template #error>
                  <el-icon class="c-[--el-color-primary]" :size="36">
                    <CircleCloseFilled />
                  </el-icon>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="昵称" prop="nickname" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="手机号" prop="mobile" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="邮箱" prop="email" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="等级" prop="level.name" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="用户性别" prop="sex" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tag-options="userSexOptions" :value="scope.row.sex"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" width="180px" align="center"></el-table-column>
        <el-table-column
          label="操作"
          align="left"
          width="350"
          fixed="right"
          v-auth="['system:role:update', 'system:role:delete']"
        >
          <template #default="{ row }">
            <el-button type="primary" size="small" plain @click="handleUpdate(row)" v-auth="['system:role:update']">
              修改
            </el-button>
            <el-button type="primary" size="small" plain @click="handleDetail(row)" v-auth="['system:user:role']">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koi-confirm="handleConfirm"
        @koi-cancel="handleCancel"
        :loading="confirmLoading"
      >
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="登录账号" prop="username">
                  <el-input v-model="form.username" placeholder="请输入登录账号" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户名称" prop="nickname">
                  <el-input v-model="form.nickname" placeholder="请输入用户名称" clearable />
                </el-form-item>
              </el-col>

              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" v-if="title == '用户添加'">
                <el-form-item label="用户密码" prop="password">
                  <el-input v-model="form.password" placeholder="新增账户密码默认 123456" disabled clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" v-if="title == '用户修改'">
                <el-form-item label="用户密码" prop="password">
                  <el-input v-model="form.password" placeholder="填写后修改密码" clearable />
                </el-form-item>
              </el-col>

              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择用户状态" clearable>
                    <el-option label="启用" :value="0" />
                    <el-option label="禁用" :value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户头像" prop="avatar">
                  <KoiUploadImage v-model:imageUrl="form.avatar">
                    <template #content>
                      <el-icon>
                        <Avatar />
                      </el-icon>
                      <span>请上传头像</span>
                    </template>
                    <template #tip>图片最大为 3M</template>
                  </KoiUploadImage>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户备注" prop="remark">
                  <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入用户备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDrawer>

      <KoiDrawer ref="koiDetailDrawerRef" title="用户详情" footer-hidden="true" :size="1000">
        <template #content>
          <Detail :info="info"></Detail>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="memberPage">
import { onMounted, reactive, ref } from "vue";
import { koiMsgError, koiMsgSuccess, koiMsgWarning, koiNoticeError, koiNoticeSuccess } from "@/utils/koi.ts";
import { add, getById, listPage, update } from "@/api/member/member/index.ts";
import { koiDatePicker } from "@/utils/index.ts";
import Detail from "@/views/member/member/Detail.vue";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  username: "",
  nickname: "",
  mobile: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    username: "",
    nickname: "",
    mobile: ""
  };
  dateRange.value = [];
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

// 时间
const dateRange = ref();
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value, "created"));
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handleListPage();
  handleDict1();
  handleDict2();
});

// 翻译数据[用户类型]
const userTypeOptions = ref();
/** 字典翻译tag */
const handleDict1 = async () => {
  try {
    userTypeOptions.value = [
      {
        dictLabel: "系统用户",
        dictValue: "1",
        dictTag: "",
        dictColor: ""
      },
      {
        dictLabel: "注册用户",
        dictValue: "2",
        dictTag: "warning",
        dictColor: ""
      }
    ];
    // const res: any = await listDataByType("sys_user_type");
    // userTypeOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError("数据字典查询失败，请刷新重试");
  }
};

// 翻译数据[用户性别]
const userSexOptions = ref();
/** 字典翻译tag */
const handleDict2 = async () => {
  try {
    userSexOptions.value = [
      { dictLabel: "男", dictValue: "1", dictTag: "", dictColor: "" },
      { dictLabel: "女", dictValue: "2", dictTag: "danger", dictColor: "" },
      { dictLabel: "未知", dictValue: "3", dictTag: "info", dictColor: "" }
    ];
    // const res: any = await listDataByType("sys_user_sex");
    // console.log("字典数据", res.data);
    // userSexOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError("数据字典查询失败，请刷新重试");
  }
};

const ids = ref([]); // 选中数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  // console.log(selection);
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "用户添加";
  form.value.status = "0";
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("添加");
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  console.log("回显数据ID", id);
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await getById(id);
    console.log(res.data);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "用户修改";
  const id = row ? row.id : ids.value[0];
  if (id == null || id == "") {
    koiMsgError("请选中需要修改的数据");
  }
  console.log(id);
  // 回显数据
  handleEcho(id);
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("修改");
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("用户类型管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  username: "",
  nickname: "",
  status: "",
  avatar: "",
  phone: "",
  remark: ""
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    username: "",
    nickname: "",
    status: "",
    avatar: "",
    phone: "",
    remark: ""
  };
};

/** 表单规则 */
const rules = reactive({
  username: [{ required: true, message: "请输入用户名字", trigger: "blur" }],
  nickname: [{ required: true, message: "请输入用户类型", trigger: "blur" }],
  status: [{ required: true, message: "请输入选择用户状态", trigger: "blur" }]
});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        if (form.value.id != null && form.value.id != "") {
          await update(form.value);
        } else {
          await add(form.value);
        }
        koiNoticeSuccess("操作成功");
        koiDrawerRef.value.koiQuickClose();
        resetForm();
        handleListPage();
      } catch (error) {
        console.log(error);
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        confirmLoading.value = false;
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};
const info = ref();
// 分配角色弹出框
const koiDetailDrawerRef = ref();
/** 分配角色 */
const handleDetail = (row: any) => {
  getById(row.id).then(res => {
    info.value = res.data;
    koiDetailDrawerRef.value.koiOpen();
  });
};

</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
  height: 400px;
}
</style>
